<template>
	<div class="article-list">
		<van-pull-refresh
			v-model="isreFreshLoading"
			@refresh="onRefresh"
			:success-text="refreshSuccessText"
			:success-duration="1500"
		>
			<van-list
				v-model="loading"
				:finished="finished"
				finished-text="没有更多了"
				:error.sync="error"
				error-text="请求失败，点击重新加载"
				@load="onLoad"
			>
      <AticleItem v-for="(article, index) in list"
					:key="index" :article='article'></AticleItem>
				<!-- <van-cell
					v-for="(article, index) in list"
					:key="index"
					:title="article.title"
				/> -->
			</van-list>
		</van-pull-refresh>
	</div>
</template>

<script>
import { getArticles } from '@/api/articles'
import AticleItem from '@/components/article-item'
export default {
	props: {
		channel: {
			type: Object,
			required: true,
		},
	},
	data() {
		return {
			list: [], // 存储列表数据的数组
			loading: false, // 控制加载中 loading 状态
			finished: false, // 控制数据加载结束的状态
			pre_timestamp: null,
			error: false,
			isreFreshLoading: false,
			refreshSuccessText: '刷新成功',
		}
	},
  components:{
AticleItem
  },
	methods: {
		async onLoad() {
			// 异步更新数据
			//  ajax 请求
			try {
				const { data } = await getArticles({
					channel_id: this.channel.id,
					timestamp: this.pre_timestamp || Date.now(),
					with_top: 1,
				})

				console.log(data)
				const { results } = data.data
				this.list.push(...results)
				// 加载状态结束
				this.loading = false
				// 测试错误提示
				// if(Math.random()>0.2){
				//   JSON.parse('ssdfff')
				// }

				if (results.length) {
					this.timestamp = data.data.pre_timestamp
				} else {
					this.finished = true
				}
				// 数据全部加载完成
			} catch (err) {
				console.log(err)
				this.loading = false
				this.error = true
			}
		},
		async onRefresh() {
			try {
				const { data } = await getArticles({
					channel_id: this.channel.id,
					timestamp: Date.now(),
					with_top: 1,
				})
        // 测试错误提示
				if(Math.random()>0.2){
				  JSON.parse('ssdfff')
				}
				const { results } = data.data
				this.list.unshift(...results)
				//  关闭下拉刷新的loading状态
				this.isreFreshLoading = false
				//  提示成功
				this.refreshSuccessText = `刷新成功，更新了${results.length}条`
  
			} catch (err) {
				console.log(err)
				this.isreFreshLoading = false
				this.$toast('刷新失败')
			}
		},
	},
}
</script>

<style scoped lang="less">
.article-list {
  // 百分比单位是相对于父元素的
  // height: 100%;

  // 视口（在移动端是布局视口）单位：vw 和 vh，不受父元素影响
  // 1vw = 视口宽度的百分之一
  // 1vh = 视口高度的百分之一
  height: 79vh;
  overflow-y: auto;
}
</style>
